<template>
  <el-dialog v-model="drawer" :title="title" width="800px" :append-to-body="true" @close="close">
    <el-form :model="form" :rules="rules" size="small" label-width="120px" ref="ruleRefForm" class="refForm">
        <el-form-item label="模板名称:" prop="name">
            <el-input v-model="form.name" placeholder="请输入模板名称"></el-input>
        </el-form-item>
        <el-form-item label="计费方式:" prop="type">
            <el-radio-group v-model="form.valuationModel" @change="selectValuationModel">
                <el-radio :label="1">按件数</el-radio>
                <el-radio :label="2">按重量</el-radio>
                <el-radio :label="3">按体积</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="配送区域及运费:" prop="area">
            <el-table :data="form.transportMode" size="small" border>
                <el-table-column label="可配送区域" prop="area">
                    <template #default="scope">
                        <template v-for="(item, index) in scope.row.area">{{item.label}}<template v-if="index < scope.row.area.length - 1">,</template></template>
                    </template>
                </el-table-column>
                <el-table-column :label="firstNumLabel" prop="firstNum" align="center">
                    <template #default="scope">
                        <el-input-number v-model="scope.row.firstNum" :min="1" style="width: 80px"></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column label="首费（元）" prop="fee" align="center">
                    <template #default="scope">
                        <el-input-number v-model="scope.row.firstPrice" :min="0" style="width: 80px"></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column :label="continueNumLabel" prop="secondNum" align="center">
                    <template #default="scope">
                        <el-input-number v-model="scope.row.continueNum" :min="1" style="width: 80px"></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column label="续费" prop="secondFee" align="center">
                    <template #default="scope">
                        <el-input-number v-model="scope.row.continuePrice" :min="0" style="width: 80px"></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template #default="scope">
                        <!-- <el-button type="primary" size="small" link v-if="scope.$index > 0" @click="delItem('transportMode',scope.$index)">删除</el-button> -->
                        <el-button type="primary" size="small" link @click="delItem('transportMode',scope.$index)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-button size="small" type="primary" style="margin-top:10px" @click="addTransportMode">单独添加配送区域</el-button>
        </el-form-item>
        <el-form-item label="指定包邮条件:" prop="isInclPostageByif">
            <el-radio-group v-model="form.isInclPostageByif">
                <el-radio :label="1">开启</el-radio>
                <el-radio :label="0">关闭</el-radio>
            </el-radio-group>
			 <el-table v-if="form.isInclPostageByif == 1"  :data="form.freeConditions" size="small" border>
			<el-table-column label="包邮区域" prop="area">
			        <template #default="scope">
			            <template v-for="(item, index) in scope.row.area">{{item.label}}<template v-if="index < scope.row.area.length - 1">,</template></template>
			        </template>
			    </el-table-column>
			    <el-table-column :label="pieceNumLabel" prop="pieceNum" align="center">
			        <template #default="scope">
			            <el-input-number v-model="scope.row.pieceNum" :min="1" style="width: 80px"></el-input-number>
			        </template>
			    </el-table-column>
			    <el-table-column label="操作" align="center">
			        <template #default="scope">
			            <el-button type="primary" size="small" link  @click="delItem('freeConditions',scope.$index)">删除</el-button>
			        </template>
			    </el-table-column>
			</el-table>
			<el-button size="small" v-if="form.isInclPostageByif == 1" type="primary" style="margin-top:10px" @click="addInclPostageByif">单独指定包邮区域</el-button>
			
        </el-form-item>
        <el-form-item v-if="false"  label="指定不送达:" prop="noDelivery">
            <el-radio-group v-model="form.noDelivery">
                <el-radio :label="1">开启</el-radio>
                <el-radio :label="0">关闭</el-radio>
            </el-radio-group>
			<el-table v-if="form.noDelivery == 1"  :data="form.noDeliverys" size="small" border>
			<el-table-column label="不可配送区域" prop="area">
			        <template #default="scope">
			            <template v-for="(item, index) in scope.row.area">{{item.label}}<template v-if="index < scope.row.area.length - 1">,</template></template>
			        </template>
			    </el-table-column>
			    <el-table-column label="操作" align="center">
			        <template #default="scope">
			            <el-button type="primary" size="small" link  @click="delItem('noDeliverys',scope.$index)">删除</el-button>
			        </template>
			    </el-table-column>
			</el-table>
			<el-button size="small" v-if="form.noDelivery == 1" type="primary" style="margin-top:10px" @click="addNoDelivery">单独指定不送达区域</el-button>
        </el-form-item>
        <el-form-item label="是否默认:" prop="isDefault">
			<el-radio-group v-model="form.isDefault">
			    <el-radio :label="0">否</el-radio>
			    <el-radio :label="1">是</el-radio>
			</el-radio-group>
        </el-form-item>
    </el-form>
    <el-row class="footer-fixed">
        <el-button type="primary" size="small" @click="submitForm(ruleRefForm)">保存</el-button>
        <el-button size="small" @click="resetForm(ruleRefForm)">取消</el-button>
    </el-row>
    <area-detail v-model:dialogArea="dialogArea" :area-form="areaForm" @onAreaSubmit="getAreaSubmit"></area-detail>
  </el-dialog>
</template>

<script>
import { computed, reactive, toRefs, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import AreaDetail from './AreaDetail.vue'
import { create,update } from '/@/api/pms/freight'
export default {
    name: 'LogisticDetail',
    props: {
        dialogDrawer: {
            type: Boolean,
            default: false
        },
        title: {
            type: String,
            default: ''
        },
        defaultForm: {
            type: Object,
            default() {
                return {}
            }
        }
    },
    components: {
        AreaDetail
    },
    setup(props, context) {
        const { dialogDrawer, defaultForm } = toRefs(props)
        const ruleRefForm = ref()
        const drawer = computed({
            get: () => dialogDrawer.value,
            set: val => {
                context.emit('update:dialogDrawer', val)
            }
        })
        const form = computed({
            get: () => defaultForm.value,
            set: val => {
                context.emit('update:defaultForm', val)
            }
        })
        const state = reactive({
            rules: {
                name: [{ required: true, message: '请输入规格模板名称', trigger: 'blur' }]
            },
            dialogArea: false,
            areaForm: [],
			addType: 'transportMode',
			firstNumLabel: '首件',
			continueNumLabel:'续件',
			pieceNumLabel:'包邮条件'
        })
		
		
		const selectValuationModel = (v) => {
			let firstNumLabel = '首件'
			let continueNumLabel = '续件'
			let pieceNumLabel = '包邮件数'
			 if(v == 1){
				firstNumLabel = firstNumLabel+'重量(KG)'
				continueNumLabel = continueNumLabel+'重量(KG)'
				pieceNumLabel = '包邮重量(KG)'
			}else if(v == 2){
				firstNumLabel = firstNumLabel+'体积(m³)'
				continueNumLabel = continueNumLabel+'体积(m³)'
				pieceNumLabel = '包邮体积(m³)'
			}
			state.firstNumLabel= firstNumLabel
			state.continueNumLabel=continueNumLabel
			state.pieceNumLabel=pieceNumLabel
			
		}
        const delItem = (type,index) => {
			form.value[type].splice(index, 1)
        }
        const addSingle = (val) => {
            state.areaForm = []
            form.value[val].forEach(item => {
                item.area.forEach(cim => {
                    if (cim.id != 0) {
                        if(cim.city){
                            cim.city.forEach(citrm => {
                                citrm.disabled = true
                            })
                        }
                        cim.disabled = true
                        state.areaForm.push(cim)
                    }

                })
            });
            state.dialogArea = true
			state.addType = val
        }
		const addTransportMode = () => {
		    addSingle('transportMode') 
		}
		const addInclPostageByif = () => {
			addSingle('freeConditions') 
		}
		const addNoDelivery = () => {
		   addSingle('noDeliverys')
		}
        const submitForm = async (formEl) => {
			
            if (!formEl) return
            await formEl.validate((valid) => {
                if (valid) {
					let data = form.value
					if(data.id != null){
						update(data).then(res=>{
							if(res.code == 0){
							 ElMessage.success("修改成功");
							 context.emit('onDetailSubmit', true)
							}else{
							 ElMessage.error("修改失败");
							}
						})
					}else{
						create(data).then(res=>{
							if(res.code == 0){
							 ElMessage.success("添加成功");
							 context.emit('onDetailSubmit', true)
							}else{
							 ElMessage.error("添加失败");
							}
						})
					}
                    
                }
            })
        }
        const resetForm = (formEl) => {
            if (!formEl) return
            context.emit('update:dialogDrawer', false)
            formEl.resetFields()
        }
        const close = () => {
            context.emit('update:dialogDrawer', false)
        }
        const getAreaSubmit = (data) => {
            console.log(form.value[state.addType]);
            console.log(data);
            if(data.length > 0) {
				if(form.value[state.addType] == null){
					form.value[state.addType] = []
				}
				let list = []
                data.forEach(item => {
                    if (!item.disabled) {
                       list.push(item) 
                    }
                })
                form.value[state.addType].push({
                   area: list,
                   firstNum: 1,
                   firstPrice: 0,
                   continueNum: 1,
                   continuePrice: 0,
				   // 指定包邮的时候用到
				   pieceNum:1
                })
            }
        }
        return {
            drawer,
            form,
            delItem,
            addSingle,
            ruleRefForm,
            submitForm,
            resetForm,
            close,
            getAreaSubmit,
			addInclPostageByif,
			addNoDelivery,
			addTransportMode,
			selectValuationModel,
            ...toRefs(state)
        }
    }
}
</script>

<style scoped>
.refForm{
    padding-bottom: 80px;
}
.footer-fixed{
    position: absolute;
    left: 0;
    bottom: 0;
    right: 0;
    padding: 10px;
    background: #fff;
    z-index: 999;
    display: flex;
    justify-content: center;
    box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 5px 0px, rgba(0, 0, 0, 0.1) 0px 0px 1px 0px;
}
</style>